<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<div class="container mx-auto px-4 py-8 max-w-6xl">
    <header class="mb-8 text-center">
        <h1 class="text-4xl font-bold text-gray-800 mb-2">用户管理系统</h1>
        <p class="text-gray-600">新增和查询用户信息</p>
    </header>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 新增用户表单 -->
        <div class="bg-white rounded-lg shadow-md p-6 lg:col-span-1">
            <h2 class="text-2xl font-semibold mb-4 text-gray-700 flex items-center">
                <i class="fa fa-user-plus mr-2 text-blue-500"></i>新增用户
            </h2>
            <form id="addUserForm" class="space-y-4">
                <div>
                    <label for="name" class="block text-gray-700 mb-1">姓名</label>
                    <input type="text" id="name" name="name" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label for="email" class="block text-gray-700 mb-1">邮箱</label>
                    <input type="email" id="email" name="email" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label for="age" class="block text-gray-700 mb-1">年龄</label>
                    <input type="number" id="age" name="age"
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <button type="submit" class="w-full bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-200">
                    <i class="fa fa-save mr-1"></i>保存用户
                </button>
            </form>
            <div id="addUserMessage" class="mt-4 hidden"></div>
        </div>

        <!-- 查询区域 -->
        <div class="lg:col-span-2 space-y-6">
            <!-- 按ID查询 -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-2xl font-semibold mb-4 text-gray-700 flex items-center">
                    <i class="fa fa-search mr-2 text-green-500"></i>按ID查询用户
                </h2>
                <div class="flex space-x-2">
                    <input type="number" id="userId" placeholder="输入用户ID"
                           class="flex-grow px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500">
                    <button id="searchByIdBtn" class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-md transition duration-200">
                        <i class="fa fa-search mr-1"></i>查询
                    </button>
                </div>
                <div id="userByIdResult" class="mt-4 hidden"></div>
            </div>

            <!-- 查询所有用户 -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-2xl font-semibold text-gray-700 flex items-center">
                        <i class="fa fa-users mr-2 text-purple-500"></i>所有用户
                    </h2>
                    <button id="getAllUsersBtn" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 rounded-md transition duration-200">
                        <i class="fa fa-refresh mr-1"></i>刷新列表
                    </button>
                </div>
                <div id="allUsersResult" class="overflow-x-auto">
                    <table class="min-w-full bg-white">
                        <thead>
                        <tr class="bg-gray-100">
                            <th class="py-2 px-4 border-b">ID</th>
                            <th class="py-2 px-4 border-b">姓名</th>
                            <th class="py-2 px-4 border-b">邮箱</th>
                            <th class="py-2 px-4 border-b">年龄</th>
                            <th class="py-2 px-4 border-b">创建时间</th>
                        </tr>
                        </thead>
                        <tbody id="usersTableBody">
                        <!-- 用户数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const baseUrl = 'http://localhost:8000/api/users';

    // 新增用户
    document.getElementById('addUserForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const user = {
            name: document.getElementById('name').value,
            email: document.getElementById('email').value,
            age: document.getElementById('age').value ? parseInt(document.getElementById('age').value) : null
        };

        try {
            const response = await fetch(baseUrl, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(user)
            });

            const messageElement = document.getElementById('addUserMessage');
            messageElement.classList.remove('hidden', 'bg-green-100', 'bg-red-100', 'text-green-800', 'text-red-800', 'p-3', 'rounded-md');

            if (response.ok) {
                const newUser = await response.json();
                messageElement.classList.add('bg-green-100', 'text-green-800', 'p-3', 'rounded-md');
                messageElement.textContent = `用户创建成功！ID: ${newUser.id}`;
                document.getElementById('addUserForm').reset();
                getAllUsers();
            } else {
                messageElement.classList.add('bg-red-100', 'text-red-800', 'p-3', 'rounded-md');
                messageElement.textContent = '创建用户失败，请检查输入信息';
            }
        } catch (error) {
            console.error('Error adding user:', error);
            const messageElement = document.getElementById('addUserMessage');
            messageElement.classList.remove('hidden');
            messageElement.classList.add('bg-red-100', 'text-red-800', 'p-3', 'rounded-md');
            messageElement.textContent = '服务器连接失败';
        }
    });

    // 按ID查询用户
    document.getElementById('searchByIdBtn').addEventListener('click', async () => {
        const userId = document.getElementById('userId').value;
        if (!userId) {
            alert('请输入用户ID');
            return;
        }

        try {
            const response = await fetch(`${baseUrl}/${userId}`);
            const resultElement = document.getElementById('userByIdResult');
            resultElement.classList.remove('hidden', 'bg-white', 'border', 'border-gray-200', 'p-4', 'rounded-md');

            if (response.ok) {
                const user = await response.json();
                resultElement.classList.add('bg-white', 'border', 'border-gray-200', 'p-4', 'rounded-md');
                resultElement.innerHTML = `
                        <h3 class="font-semibold text-lg mb-2">用户信息</h3>
                        <p><strong>ID:</strong> ${user.id}</p>
                        <p><strong>姓名:</strong> ${user.name}</p>
                        <p><strong>邮箱:</strong> ${user.email}</p>
                        <p><strong>年龄:</strong> ${user.age || '未提供'}</p>
                        <p><strong>创建时间:</strong> ${new Date(user.createdAt).toLocaleString()}</p>
                    `;
            } else {
                resultElement.classList.add('bg-white', 'border', 'border-gray-200', 'p-4', 'rounded-md');
                resultElement.innerHTML = '<p class="text-red-500">未找到该用户</p>';
            }
        } catch (error) {
            console.error('Error searching user:', error);
            const resultElement = document.getElementById('userByIdResult');
            resultElement.classList.remove('hidden');
            resultElement.classList.add('bg-white', 'border', 'border-gray-200', 'p-4', 'rounded-md');
            resultElement.innerHTML = '<p class="text-red-500">服务器连接失败</p>';
        }
    });

    // 获取所有用户
    async function getAllUsers() {
        try {
            const response = await fetch(baseUrl);
            if (response.ok) {
                const users = await response.json();
                const tableBody = document.getElementById('usersTableBody');
                tableBody.innerHTML = '';

                if (users.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="5" class="py-2 px-4 border-b text-center">暂无用户数据</td></tr>';
                    return;
                }

                users.forEach(user => {
                    const row = document.createElement('tr');
                    row.className = 'hover:bg-gray-50';
                    row.innerHTML = `
                            <td class="py-2 px-4 border-b">${user.id}</td>
                            <td class="py-2 px-4 border-b">${user.name}</td>
                            <td class="py-2 px-4 border-b">${user.email}</td>
                            <td class="py-2 px-4 border-b">${user.age || '-'}</td>
                            <td class="py-2 px-4 border-b">${new Date(user.createdAt).toLocaleString()}</td>
                        `;
                    tableBody.appendChild(row);
                });
            }
        } catch (error) {
            console.error('Error getting all users:', error);
            const tableBody = document.getElementById('usersTableBody');
            tableBody.innerHTML = '<tr><td colspan="5" class="py-2 px-4 border-b text-center text-red-500">获取用户数据失败</td></tr>';
        }
    }

    // 初始化和刷新
    document.addEventListener('DOMContentLoaded', getAllUsers);
    document.getElementById('getAllUsersBtn').addEventListener('click', getAllUsers);
</script>
</body>
</html>